package com.lzxzjy.web.servlet;

import com.alibaba.fastjson.JSON;
import com.lzxzjy.pojo.*;
import com.lzxzjy.serivce.BorrowInfoService;
import com.lzxzjy.serivce.ReaderService;
import com.lzxzjy.serivce.impl.BorrowINfoServiceImpl;
import com.lzxzjy.serivce.impl.ReaderServiceImpl;
import com.lzxzjy.util.EncryptionUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@WebServlet("/reader/*")
public class ReaderServlet extends BaseServlet {
    private final ReaderService readerService = new ReaderServiceImpl();

    public void getUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Reader reader = (Reader) session.getAttribute("reader");
        String readerLine = "{ \"readerId\":" + reader.getReaderId() + ",\"readerName\":\"" + reader.getReaderName() + "\"}";
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(readerLine);
    }


    private int getReaderState(String bookStateValue) {
        if ("true".equals(bookStateValue)) {
            return 1;
        } else if ("false".equals(bookStateValue)) {
            return 0;
        }
        return -1;
    }

    public void insertReader(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        BufferedReader readerReader = request.getReader();
        String readerLine = readerReader.readLine();
        Reader reader = JSON.parseObject(readerLine, Reader.class);
        reader.setReaderState(1);
        reader.setReaderPassword(EncryptionUtil.encrypt(reader.getReaderPassword()));
        if (reader.isEmpty()) {
            response.getWriter().write("empty");
            return;
        }
        boolean isSuccess = false;
        try {
            isSuccess = readerService.insertReader(reader);
        } catch (Exception e) {
            if(e.getMessage().contains("Duplicate entry '") && e.getMessage().contains("' for key 'tb_reader.uk_reader_email'")) {
                response.getWriter().write("email");
                return;
            }
        }
        response.getWriter().write(isSuccess ? "success" : "failure");
    }

    private int[] toIntArrayReaderIds(String readerLine) {
        Reader[] readers = JSON.parseObject(readerLine, Reader[].class);
        StringBuilder stringIds = new StringBuilder("[");
        for (Reader reader : readers) {
            stringIds.append(reader.getReaderId());
            stringIds.append(",");
        }
        stringIds.replace(stringIds.length() - 1, stringIds.length(), "]");
        return JSON.parseObject(String.valueOf(stringIds), int[].class);
    }

    private boolean readerIsBorrow(int readerId) {
        BorrowInfoService borrowInfoService = new BorrowINfoServiceImpl();
        return borrowInfoService.selectBorrowInfoByPageAndBookTerms(new BorrowInfo(null, "%%", readerId, "%%", null, null, null), 1, 1).getTotalCount() != 0;
    }

    public void deleteReaderByIds(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        BufferedReader readerReader = request.getReader();
        String readerLine = readerReader.readLine();
        if ("[]".equals(readerLine)) {
            return;
        }
        int[] readerIds = toIntArrayReaderIds(readerLine);
        for (int id : readerIds) {
            if (readerIsBorrow(id)) {
                response.getWriter().write("notEmpty");
                return;
            }
        }
        boolean isSuccess = readerService.deleteReaderByIds(readerIds);
        if (isSuccess) {
            response.getWriter().write("success");
        } else {
            response.getWriter().write("failure");
        }
    }

    public void deleteReaderById(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int readerId = Integer.parseInt(request.getParameter("readerId"));
        if (readerIsBorrow(readerId)) {
            response.getWriter().write("notEmpty");
            return;
        }
        boolean isSuccess = readerService.deleteReaderById(readerId);
        if (isSuccess) {
            response.getWriter().write("success");
        } else {
            response.getWriter().write("failure");
        }
    }

    public void updateReaderById(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        BufferedReader readerReader = request.getReader();
        String readerLine = readerReader.readLine();
        String readerStateValue = request.getParameter("readerStateValue");
        Reader reader = JSON.parseObject(readerLine, Reader.class);
        if (getReaderState(readerStateValue) != -1) {
            reader.setReaderState(getReaderState(readerStateValue));
        }
        reader.setReaderPassword(EncryptionUtil.encrypt(reader.getReaderPassword()));
        boolean isSuccess = false;
        try {
            isSuccess = readerService.updateReaderById(reader);
        } catch (Exception e) {
            if(e.getMessage().contains("Duplicate entry '") && e.getMessage().contains("' for key 'tb_reader.uk_reader_email'")) {
                response.getWriter().write("email");
                return;
            }
        }
        if (isSuccess) {
            response.getWriter().write("success");
        } else {
            response.getWriter().write("failure");
        }
    }

    public void selectReaderByPageAndTerms(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        BufferedReader readerReader = request.getReader();
        String readerLine = readerReader.readLine();
        int currentPage = Integer.parseInt(request.getParameter("currentPage"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));


        Reader reader = JSON.parseObject(readerLine, Reader.class);
        reader.setReaderName("%" + reader.getReaderName() + "%");
        reader.setReaderPhone("%" + reader.getReaderPhone() + "%");
        reader.setReaderEmail("%" + reader.getReaderEmail() + "%");


        PageBean<Reader> readerPageBean = readerService.selectReaderByPageAndTerms(reader, currentPage, pageSize);
        for (Reader r : readerPageBean.getRows()) {
            r.setReaderPassword(EncryptionUtil.decrypt(r.getReaderPassword()));
        }
        String toJSONString = JSON.toJSONString(readerPageBean);

        // 写数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(toJSONString);
    }
}
